package com.martinwj.camera2demo.module;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.AudioManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.InputFilter;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.martinwj.camera2demo.MainActivity;
import com.martinwj.camera2demo.R;
import com.martinwj.camera2demo.constant.CameraConstant;
import com.martinwj.camera2demo.ui.AutoFitTextureView;
import com.martinwj.camera2demo.ui.PictureActivity;
import com.martinwj.camera2demo.utils.ErrorDialog;
import com.martinwj.camera2demo.utils.ImageUtils;
import com.martinwj.camera2demo.utils.MediaFunc;
import com.martinwj.camera2demo.utils.PermissionDialog;
import com.martinwj.camera2demo.utils.TimeFilter;
import com.martinwj.camera2demo.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * author: wj
 * created on: 2021/5/28 13:51
 * description:
 */
public class CameraFragment extends Fragment
        implements View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {

//    private PictureActivity mCameraFragment;

    private static final int SENSOR_ORIENTATION_DEFAULT_DEGREES = 90;
    private static final int SENSOR_ORIENTATION_INVERSE_DEGREES = 270;
    /**
     * 从屏幕旋转到JPEG方向的转换。
     */
    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();
    private static final SparseIntArray INVERSE_ORIENTATIONS = new SparseIntArray();

    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final int REQUEST_VIDEO_PERMISSIONS = 1;
    private static final String FRAGMENT_DIALOG = "dialog";

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }
    static {
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_0, 270);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_90, 180);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_180, 90);
        INVERSE_ORIENTATIONS.append(Surface.ROTATION_270, 0);
    }

    //缩略图参数
//    private Context sContext = getContext();
//    private static final String[] STORE_IMAGES = {
//            MediaStore.Images.Thumbnails._ID,
//    };
    //拍照按钮参数
    private ImageView iv_pictures;
    //录像参数
    private MediaRecorder mMediaRecorder;
    private int mRecordingVideo = 3; // 1:开始录像  2：停止录像  3：拍照
    private String mNextVideoAbsolutePath;
    private CameraCaptureSession mPreviewSession;
    private int mCaptureRate = 30;
    //计时器
    Chronometer time;

    //ui控件参数
    private ImageView iv_info;
    private ImageView iv_flash;
    private ImageView iv_setting;
    private ImageView iv_change;
    private TextView tv_delayed;
    private TextView tv_continuous;
    private TextView tv_pictures;
    private TextView tv_videotapes;
    private TextView tv_slowMotion;
    // 倒计时
    private EditText et_time;
//    private HandlerThread mTimeThread;
    private Handler mTimeHandler;
//    private static final Handler timeHandler = new Handler(Looper.getMainLooper());2

    private boolean isCountDownState = false;

    // 人脸数量
    private TextureView tv_faceView;//用于标注人脸
    int[] faceDetectModes;
    int face;
    Paint pb;
    Size cPixelSize; // 相机成像尺寸

    //闪关灯标识
    private int mFlash = 0;
    // 前后置摄像头切换参数，0：后置， 1：前置。
    private int mCameraState = 0;
    // 分辨率：0:原始分辨率  1：分辨率1456x1456   2：分辨率480x640   3：分辨率720x1280
    private static int mRatio = 0;
    // 水印标志： 0: 不添加水印   1：添加水印
    private int mWatermark = 0;
    // 水印字
    TextView textView;

    private Size[] sizeArr;


    // 音频文件
    MediaPlayer cameraMP;

    /**
     * TAG
     */
    private static final String TAG = "CameraFragment";

    /**
     * 相机状态：显示相机预览。
     */
    private static final int STATE_PREVIEW = 0;

    /**
     * 相机状态：等待焦点被锁定。
     */
    private static final int STATE_WAITING_LOCK = 1;

    /**
     * 相机状态：等待曝光为预拍摄状态。
     */
    private static final int STATE_WAITING_PRECAPTURE = 2;

    /**
     * 相机状态：等待曝光状态为预拍摄以外的状态。
     */
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;

    /**
     * 相机状态：已拍摄照片。
     */
    private static final int STATE_PICTURE_TAKEN = 4;

    /**
     * Camera2 API保证的最大预览宽度
     */
    private static final int MAX_PREVIEW_WIDTH = 1920;

    /**
     * Camera2 API保证的最大预览高度
     */
    private static final int MAX_PREVIEW_HEIGHT = 1080;

    /**
     * TextureView.SurfaceTextureListener 处理一个 TextureView
     */
    private final TextureView.SurfaceTextureListener mSurfaceTextureListener
            = new TextureView.SurfaceTextureListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
            configureTransform(width, height);
        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture texture) {
        }

    };

    /**
     * 缩略图
     */
    private static ImageView mPicture_tv;
    private static Bitmap picture;

    @SuppressLint("HandlerLeak")
    private static final Handler pictureHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 1){
                mPicture_tv.setImageBitmap(picture);
            }
        }
    };

    /**
     * 当前相机的ID
     */
    private String mCameraId;

    /**
     * 用于相机预览
     */
    private AutoFitTextureView mTextureView;

    /**
     * 用于相机预览的  CameraCaptureSession
     */
    private CameraCaptureSession mCaptureSession;

    /**
     * 对打开的{@link CameraDevice}的引用。一个CameraDevice对应一个摄像头设备
     */
    private CameraDevice mCameraDevice;

    /**
     * 相机预览的{@link android.util.Size}。
     */
    private Size mPreviewSize;

    /**
     * {@link CameraDevice}更改其状态时，将调用{@link CameraDevice.StateCallback}。
     */
    private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {

        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            // 这个方法在摄像机打开时被调用。我们从这里开始相机预览。
            mCameraOpenCloseLock.release();
            mCameraDevice = cameraDevice;
            createCameraPreviewSession();
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int error) {
            mCameraOpenCloseLock.release();
            cameraDevice.close();
            mCameraDevice = null;
            Activity activity = getActivity();
            if (null != activity) {
                activity.finish();
            }
        }

    };

    /**
     * 用于运行不应阻塞UI的任务的附加线程。
     */
    private HandlerThread mBackgroundThread;

    /**
     * {@link Handler} 用于在后台运行任务。
     */
    private Handler mBackgroundHandler;

    /**
     * {@link ImageReader}处理静态图像捕获。
     */
    private ImageReader mImageReader;

    /**
     * 这是我们图片的输出文件。
     */
    private File mFile;

    /**
     * 这是{@link ImageReader}的回调对象。当准备好保存静止图像时，将调用“onImageAvailable”。
     */
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener
            = new ImageReader.OnImageAvailableListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onImageAvailable(ImageReader reader) {
            mBackgroundHandler.post(new ImageSaver(reader.acquireNextImage(), mFile, mCameraState, mRatio, mWatermark, getContext()));
        }

    };

    /**
     * {@link CaptureRequest.Builder}用于摄像机预览
     */
    private CaptureRequest.Builder mPreviewRequestBuilder;

    /**
     * {@link #mPreviewRequestBuilder}生成的{@link CaptureRequest}
     */
    private CaptureRequest mPreviewRequest;

    /**
     * 相机当前的拍照状态。
     *
     * @see #mCaptureCallback
     */
    private int mState = STATE_PREVIEW;

    /**
     * {@link Semaphore} 可防止应用程序在关闭相机前退出。
     */
    private final Semaphore mCameraOpenCloseLock = new Semaphore(1);

    /**
     * 当前的相机设备是否支持Flash。
     */
    private boolean mFlashSupported;

    /**
     * 相机传感器的方向
     */
    private int mSensorOrientation;

    /**
     * {@link CameraCaptureSession.CaptureCallback}处理与JPEG捕获有关的事件。
     */
    private final CameraCaptureSession.CaptureCallback mCaptureCallback
            = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {
            switch (mState) {
                case STATE_PREVIEW: {
                    // 相机预览正常工作时，我们无需执行任何操作。
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        // CONTROL_AE_STATE在某些设备上可以为空
                        // 相机预览正常工作时，我们无需执行任何操作。
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE在某些设备上可以为null
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE在某些设备上可以为null
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session,
                                        @NonNull CaptureRequest request,
                                        @NonNull CaptureResult partialResult) {
            process(partialResult);
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                       @NonNull CaptureRequest request,
                                       @NonNull TotalCaptureResult result) {
            process(result);
            if (System.currentTimeMillis() - lastTime_Session >= 1000) {
                CameraFragment.this.onCameraImagePreviewed(result);
                lastTime_Session = System.currentTimeMillis();
            }
//            CameraFragment.this.onCameraImagePreviewed(result);
//            Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
//            System.out.println("====人脸数====" + faces.length);
//            if (faces.length != face) {
//                Log.e("lee", faces.length + "张脸");
//                face = faces.length;
//            }
        }

    };

    private static long lastTime_Session = System.currentTimeMillis();

    /**
     * 在UI线程上显示{@link Toast}。
     *
     * @param text The message to show 显示的讯息
     */
    private void showToast(final String text) {
        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(activity, text, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 给定相机支持的{@code Size}个{@code choices}，请选择最小的一个，该大小至少与相应的纹理视图大小一样大，
     * 并且最大与相应的最大视图大小一样大，并且宽高比与指定值匹配。如果不存在这种尺寸，请选择最大尺寸，最大尺
     * 寸与相应的最大尺寸一样大，并且其宽高比与指定值匹配。
     *
     * @param choices           相机支持的预期输出类别的尺寸列表
     * @param textureViewWidth  纹理视图相对于传感器坐标的宽度
     * @param textureViewHeight 纹理视图相对于传感器坐标的高度
     * @param maxWidth          可以选择的最大宽度
     * @param maxHeight         可以选择的最大高度
     * @param aspectRatio       宽高比
     *                          最佳{@code Size}，如果没有足够大的值，则为任意值
     */
    private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                          int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {

        // 收集至少与预览Surface一样大的受支持的分辨率
        List<Size> bigEnough = new ArrayList<>();
        // 收集小于预览Surface的支持的分辨率
        List<Size> notBigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        for (Size option : choices) {
            if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                    option.getHeight() == option.getWidth() * h / w) {
                if (option.getWidth() >= textureViewWidth &&
                        option.getHeight() >= textureViewHeight) {
                    bigEnough.add(option);
                } else {
                    notBigEnough.add(option);
                }
            }
        }

        // 选择足够大的那些中的最小者。如果没有足够大的Size，则从不够大的Size中选最大的一个。
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else if (notBigEnough.size() > 0) {
            return Collections.max(notBigEnough, new CompareSizesByArea());
        } else {
            // 找不到合适的预览尺寸
            Log.e(TAG, "找不到合适的预览尺寸");
            return choices[0];
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.camera_fragment_layout, container, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {
        view.findViewById(R.id.picture).setOnClickListener(this);
        view.findViewById(R.id.info).setOnClickListener(this);

        view.findViewById(R.id.picture_iv).setOnClickListener(this);
        view.findViewById(R.id.pictures).setOnClickListener(this);
        view.findViewById(R.id.videotapes).setOnClickListener(this);
        view.findViewById(R.id.slowMotion).setOnClickListener(this);
        view.findViewById(R.id.change).setOnClickListener(this);
        view.findViewById(R.id.delayed).setOnClickListener(this);
        view.findViewById(R.id.continuous).setOnClickListener(this);
        view.findViewById(R.id.setting).setOnClickListener(this);
        view.findViewById(R.id.flash).setOnClickListener(this);

        mTextureView = (AutoFitTextureView)view.findViewById(R.id.texture);
        mPicture_tv = (ImageView) view.findViewById(R.id.picture_iv);
        iv_pictures = (ImageView) view.findViewById(R.id.picture);
        iv_info = (ImageView) view.findViewById(R.id.info);
        iv_flash = (ImageView) view.findViewById(R.id.flash);
        iv_setting = (ImageView) view.findViewById(R.id.setting);
        iv_change = (ImageView) view.findViewById(R.id.change);
        tv_videotapes = (TextView) view.findViewById(R.id.videotapes);
        tv_delayed = (TextView) view.findViewById(R.id.delayed);
        tv_pictures = (TextView) view.findViewById(R.id.pictures);
        tv_continuous = (TextView) view.findViewById(R.id.continuous);
        tv_slowMotion = (TextView) view.findViewById(R.id.slowMotion);

        tv_faceView = (TextureView) view.findViewById(R.id.tv_faceView);

        //隐藏背景色，以免标注人脸时挡住预览画面
        tv_faceView.setAlpha(0.9f);

        et_time = (EditText) view.findViewById(R.id.et_time);
        et_time.setVisibility(View.GONE);
        et_time.setText("0");
//        et_time.setFilters(new InputFilter[] { new TimeFilter() });

        textView = (TextView)view.findViewById(R.id.textView);
        time = (Chronometer)view.findViewById(R.id.time);
        time.setVisibility(View.GONE);
        textView.setVisibility(View.GONE);

        if(ImageUtils.getLatestThumbBitmap(getContext()) != null){ //如果手机记录的最新一张图片被删除，ImageUtils.getLatestThumbBitmap（）返回值为空。
            mPicture_tv.setImageBitmap(ImageUtils.getLatestThumbBitmap(getContext()));
        }else{
            mPicture_tv.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.shutter_panorama));
        }

        ImageUtils.mDatas = ImageUtils.getThumbBitmapIndexs(getContext());
        ImageUtils.mContext = getContext();
    }

    @Override
    public void onActivityCreated(android.os.Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
//        mFile = MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "CAMERA");
        setmFile();
    }

    public void setmFile() {
        this.mFile = MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "CAMERA");
    }

    public void setmFile(File mFile) {
        this.mFile = mFile;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onResume() {
        super.onResume();
        startBackgroundThread();

        // 当屏幕关闭并重新打开时，SurfaceTexture已经可用，并且不会调用“ onSurfaceTextureAvailable”。
        // 在这种情况下，我们可以打开相机并从此处开始预览（否则，我们等到SurfaceTextureListener中的曲面
        // 准备好为止）。
        if (mTextureView.isAvailable()) {
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }
    }

    @Override
    public void onPause() {
        closeCamera();
        stopBackgroundThread();
        super.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (grantResults.length != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                new PermissionDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
//                    ErrorDialog.newInstance(getString(R.string.request_permission))
//                            .show(getChildFragmentManager(), FRAGMENT_DIALOG);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 设置与摄像机相关的成员变量。
     *
     * @param width  相机预览可用尺寸的宽度
     * @param height 相机预览可用尺寸的高度
     */
    @SuppressWarnings("SuspiciousNameCombination")
    private void setUpCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            for (String cameraId : manager.getCameraIdList()) {
                CameraCharacteristics characteristics
                        = manager.getCameraCharacteristics(cameraId);

                // 在此示例中，我们不使用前置摄像头。
                Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing != null && facing == CameraCharacteristics.LENS_FACING_FRONT) {
                    continue;
                }
                cPixelSize = characteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);//获取成像尺寸，同上
                //可用于判断是否支持人脸检测，以及支持到哪种程度
                faceDetectModes = characteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);//支持的人脸检测模式
                System.out.println("=====faceDetectModes=====" + faceDetectModes.length);

                StreamConfigurationMap map = characteristics.get(
                        CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
                if (map == null) {
                    continue;
                }
                sizeArr = map.getOutputSizes(ImageFormat.JPEG);
                // 对于静态图像捕获，我们使用最大的可用尺寸。
//                Size largest = Collections.max(Arrays.asList(sizeArr), new CompareSizesByArea());
                Size largest = new Size(1920, 1080);

                // 修改图片分辨率
                //largest.getWidth(), largest.getHeight(), 1*1 2992*2992   4*3 1920*1440   16*9 1920*1080
                if(mRatio == 0){
                    mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, /*maxImages*/2);
                }else if(mRatio == 1){
                    mImageReader = ImageReader.newInstance(2992, 2992, ImageFormat.JPEG, /*maxImages*/2);
                }else if(mRatio == 2){
                    mImageReader = ImageReader.newInstance(1920, 1440, ImageFormat.JPEG, /*maxImages*/2);
                }else {
                    mImageReader = ImageReader.newInstance(1920, 1080, ImageFormat.JPEG, /*maxImages*/2);
                }
                mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);

                // 找出我们是否需要交换尺寸以获得相对于传感器坐标的预览尺寸。
                int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
                // 恒定条件下不检查
                mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
                boolean swappedDimensions = false;
                switch (displayRotation) {
                    case Surface.ROTATION_0:
                    case Surface.ROTATION_180:
                        if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                            swappedDimensions = true;
                        }
                        break;
                    case Surface.ROTATION_90:
                    case Surface.ROTATION_270:
                        if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                            swappedDimensions = true;
                        }
                        break;
                    default:
                        // 显示旋转无效：
                        Log.e(TAG, "无效的旋转显示：" + displayRotation);
                }

                Point displaySize = new Point();
                activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
                int rotatedPreviewWidth = width;
                int rotatedPreviewHeight = height;
                int maxPreviewWidth = displaySize.x;
                int maxPreviewHeight = displaySize.y;

                if (swappedDimensions) {
                    rotatedPreviewWidth = height;
                    rotatedPreviewHeight = width;
                    maxPreviewWidth = displaySize.y;
                    maxPreviewHeight = displaySize.x;
                }

                if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                    maxPreviewWidth = MAX_PREVIEW_WIDTH;
                }

                if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                    maxPreviewHeight = MAX_PREVIEW_HEIGHT;
                }

                Size[] sizes = map.getOutputSizes(SurfaceTexture.class);
                for (Size size : sizes) {
                    System.out.println(size);
                }

                //修改预览分辨率
                if(mRatio == 0){
                    // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
                    // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
                    // garbage capture data.
                    mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);
//                    mPreviewSize = new Size(rotatedPreviewWidth,rotatedPreviewHeight);//全屏预览
                }else if(mRatio == 1){
                    mPreviewSize = new Size(1456,1456);
                }else if(mRatio == 2){
                    mPreviewSize = new Size(640,480);
                }else {
                    mPreviewSize = new Size(1280,720);
                }
                // 危险！尝试使用太大的预览大小可能会超出相机总线的带宽限制，从而产生漂亮的预览，但会存储垃圾回收数据。
//                mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
//                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
//                        maxPreviewHeight, largest);

                // 我们将TextureView的长宽比调整为我们选择的预览大小。
                int orientation = getResources().getConfiguration().orientation;
                if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getWidth(), mPreviewSize.getHeight());
                } else {
                    mTextureView.setAspectRatio(
                            mPreviewSize.getHeight(), mPreviewSize.getWidth());
                }

                // 检查是否支持闪光灯。
                Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
                mFlashSupported = available == null ? false : available;

                mCameraId = cameraId;
                return;
            }
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // 当前，当使用Camera2API但运行此代码的设备不支持NPE时，将引发NPE。
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }
    }

    /**
     * 打开由{@link CameraFragment#mCameraId}指定的摄像机。
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void openCamera(int width, int height) {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestCameraPermission();
            return;
        }
        setUpCameraOutputs(width, height);
        configureTransform(width, height);
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                // 等待锁定相机打开超时。
                throw new RuntimeException("等待打开锁定相机.");
            }
            mCameraId = String.valueOf(mCameraState);
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            // 尝试锁定相机打开时中断。
            throw new RuntimeException("尝试中断打开锁定相机.", e);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestCameraPermission() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
            new PermissionDialog().show(getFragmentManager(), "PermissionDeny");
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }
    }

    /**
     * 关闭当前的{@link CameraDevice}。
     */
    private void closeCamera() {
        try {
            mCameraOpenCloseLock.acquire();
            if (null != mCaptureSession) {
                mCaptureSession.close();
                mCaptureSession = null;
            }
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
            }
            if (null != mImageReader) {
                mImageReader.close();
                mImageReader = null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("尝试中断关闭锁定相机.", e);
        } finally {
            mCameraOpenCloseLock.release();
        }
    }

    /**
     * 启动后台线程及其{@link Handler}。
     */
    @SuppressLint("HandlerLeak")
    private void startBackgroundThread() {
        mBackgroundThread = new HandlerThread("CameraBackground");
//        mTimeThread = new HandlerThread("CameraTime");
//        mTimeThread.start();
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
        mTimeHandler = new Handler() {
            @SuppressLint("HandlerLeak")
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                System.out.println(msg.what + "===============" + msg.obj);
                switch (msg.what) {
                    case CameraConstant.SEND_MESSAGE:
                        et_time.setText(String.valueOf(msg.obj));
                        break;
                }
            }
        };
    }

    /**
     * 停止后台线程及其{@link Handler}。
     */
    private void stopBackgroundThread() {
        mBackgroundThread.quitSafely();
        try {
            mBackgroundThread.join();
            mBackgroundThread = null;
            mBackgroundHandler = null;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建一个新的{@link CameraCaptureSession}用于摄像头预览。
     */
    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            // 我们将默认缓冲区的大小配置为所需的摄像机预览的大小。
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // 这是我们需要开始预览的输出Surface。
            Surface surface = new Surface(texture);

            // 我们使用输出Surface设置一个CaptureRequest.Builder。
            mPreviewRequestBuilder
                    = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(surface);

            // 在这里，我们创建了CameraCaptureSession来进行摄像机预览。
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // 相机已经关闭
                            if (null == mCameraDevice) {
                                return;
                            }

                            // 会话准备就绪后，我们开始显示预览。
                            mCaptureSession = cameraCaptureSession;
                            try {
                                // 自动对焦应连续进行相机预览。
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

                                //设置人脸检测级别
                                mPreviewRequestBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,getFaceDetectMode());

                                // 必要时会自动启用闪光灯。
                                setAutoFlash(mPreviewRequestBuilder);

                                // 最后，我们开始显示摄像机预览。
                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                        mCaptureCallback, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {
                            showToast("Failed");
                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将必要的{@link android.graphics.Matrix}转换配置为“mTextureView”。在setUpCameraOutputs中确定
     * 了摄像机预览大小并且固定了mTextureView大小之后，应调用此方法。
     *
     * @param viewWidth  `mTextureView`的宽度
     * @param viewHeight `mTextureView`的高度
     */
    private void configureTransform(int viewWidth, int viewHeight) {
        Activity activity = getActivity();
        if (null == mTextureView || null == mPreviewSize || null == activity) {
            return;
        }
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }

    /**
     * 启动捕获图像。
     */
    private void takePicture() {
        lockFocus();
    }

    /**
     * 锁定焦点是静止图像拍摄的第一步。
     */
    private void lockFocus() {
        try {
            if(mFlash == 1) {
                //开启闪光灯
                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
            }else {
                mPreviewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
            }
            // 这是告诉相机锁定焦点的方法。
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
            // 告诉mCaptureCallback等待锁。
            mState = STATE_WAITING_LOCK;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 运行预捕获序列以捕获静止图像。当我们从{@link #lockFocus()}在{@link #mCaptureCallback}中收到响
     * 应时，应调用此方法。
     */
    private void runPrecaptureSequence() {
        try {
            // 这是告诉相机触发的方法。
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
                    CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
            // 告诉mCaptureCallback等待设置预捕获序列。
            mState = STATE_WAITING_PRECAPTURE;
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取支持的最高人脸级别
     * @return
     */
    private int getFaceDetectMode() {
        System.out.println("=============getFaceDetectMode============");
        if (faceDetectModes == null) {
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        } else {
            return faceDetectModes[faceDetectModes.length - 1];
        }
    }

    /**
     * 拍摄静止图像。当我们在{@link #lockFocus()}的{@link #mCaptureCallback}中收到响应时，应调用此方法。
     */
    private void captureStillPicture() {
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }
            // 这是我们用来拍照的CaptureRequest.Builder。
            final CaptureRequest.Builder captureBuilder =
                    mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // 使用与预览相同的AE和AF模式。
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            setAutoFlash(captureBuilder);

            // 方向
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
//            if(mCameraState == 1) {
//
//            }
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback CaptureCallback
                    = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                               @NonNull CaptureRequest request,
                                               @NonNull TotalCaptureResult result) {
                    showToast("Saved: " + mFile);
                    Log.d(TAG, "======Saved====" + mFile.toString());
                    unlockFocus();
                    setmFile();
//                    CameraFragment.this.onCameraImagePreviewed(result);
                }
            };

            mCaptureSession.stopRepeating();
            mCaptureSession.abortCaptures();
            mCaptureSession.capture(captureBuilder.build(), CaptureCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从指定的屏幕旋转角度检索JPEG方向。
     *
     * @param rotation 屏幕旋转。
     * @return JPEG方向（0、90、270和360中的一个）
     */
    private int getOrientation(int rotation) {
        // 对于大多数设备，传感器方向为90，对于某些设备（例如Nexus 5X），传感器方向为270。我们必须
        // 考虑到这一点，并正确旋转JPEG。对于方向为90的设备，我们只需从ORIENTATIONS返回映射即可。
        // 对于方向为270的设备，我们需要将JPEG旋转180度。
        return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
    }

    /**
     * 释放焦点。静止图像捕获序列完成后应调用此方法。
     */
    private void unlockFocus() {
        try {
            // 重置自动对焦触发器
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                    CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            setAutoFlash(mPreviewRequestBuilder);
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
                    mBackgroundHandler);
            // 此后，相机将返回到预览的正常状态。
            mState = STATE_PREVIEW;
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback,
                    mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理相机画面处理完成事件，获取检测到的人脸坐标，换算并绘制方框
     * @param result
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void onCameraImagePreviewed(CaptureResult result) {
        Face faces[] = result.get(CaptureResult.STATISTICS_FACES);
        ToastUtils.showToast(CameraFragment.this.getContext(), "人脸个数:[" + faces.length + "]");
//        showToast("人脸个数:[" + faces.length + "]");

        Canvas canvas = tv_faceView.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//旧画面清理覆盖

        if (faces.length > 0) {
            for (int i = 0; i < faces.length; i++) {
                Rect fRect = faces[i].getBounds();
                System.out.println("=========[R" + i + "]:[left:" + fRect.left + ",top:" + fRect.top + ",right:" + fRect.right + ",bottom:" + fRect.bottom + "]");
//                showToast("[R" + i + "]:[left:" + fRect.left + ",top:" + fRect.top + ",right:" + fRect.right + ",bottom:" + fRect.bottom + "]");

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行比例换算
                //成像画面与方框绘制画布长宽比比例（同画面角度情况下的长宽比例（此处前后摄像头成像画面相对预览画面倒置（±90°），计算比例时长宽互换））
                float scaleWidth = canvas.getHeight() * 1.0f / cPixelSize.getWidth();
                float scaleHeight = canvas.getWidth() * 1.0f / cPixelSize.getHeight();
                System.out.println("=======canvas.getHeight()======" + canvas.getHeight() + "=======canvas.getWidth()=====" + canvas.getWidth());
                System.out.println("=======cPixelSize.getHeight()======" + cPixelSize.getHeight() + "=======cPixelSize.getWidth()=====" + cPixelSize.getWidth());
                System.out.println("=======scaleHeight======" + scaleHeight + "=======scaleWidth=====" + scaleWidth);

                //坐标缩放
                int l = (int) (fRect.left * scaleWidth);
                int t = (int) (fRect.top * scaleHeight);
                int r = (int) (fRect.right * scaleWidth);
                int b = (int) (fRect.bottom * scaleHeight);
                System.out.println("=============[T" + i + "]:[left:" + l + ",top:" + t + ",right:" + r + ",bottom:" + b + "]");
//                showToast("[T" + i + "]:[left:" + l + ",top:" + t + ",right:" + r + ",bottom:" + b + "]");

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行坐标转换以及原点(0,0)换算
                //人脸检测：坐标原点为相机成像画面的左上角，left、top、bottom、right以成像画面左上下右为基准
                //画面旋转后：原点位置不一样，根据相机成像画面的旋转角度需要换算到画布的左上角，left、top、bottom、right基准也与原先不一样，
                //如相对预览画面相机成像画面角度为90°那么成像画面坐标的top，在预览画面就为left。如果再翻转，那成像画面的top就为预览画面的right，且坐标起点为右，需要换算到左边
                if (mCameraState == 1) {
                    //此处前置摄像头成像画面相对于预览画面顺时针90°+翻转。left、top、bottom、right变为bottom、right、top、left，并且由于坐标原点由左上角变为右下角，X,Y方向都要进行坐标换算
                    canvas.drawRect(canvas.getWidth() - b, canvas.getHeight() - r, canvas.getWidth() - t, canvas.getHeight() - l, getPaint());
                } else {
                    //此处后置摄像头成像画面相对于预览画面顺时针270°，left、top、bottom、right变为bottom、left、top、right，并且由于坐标原点由左上角变为左下角，Y方向需要进行坐标换算
                    canvas.drawRect(canvas.getWidth() - b, l, canvas.getWidth() - t, r, getPaint());
                }
            }
        }
        tv_faceView.unlockCanvasAndPost(canvas);
    }

    /**
     * 初始化画笔
     */
    private Paint getPaint(){
        if(pb == null){
            pb =new Paint();
            pb.setColor(Color.BLUE);
            pb.setStrokeWidth(10);
            pb.setStyle(Paint.Style.STROKE);//使绘制的矩形中空
        }
        return pb;
    }

    private long currentTime;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @SuppressLint({"NonConstantResourceId", "ResourceType"})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.picture: {
                if (mRecordingVideo == 3) {
                    if (!isCountDownState) {
                        mTimeHandler.post(timeRunnable);
                    } else {
                        Toast.makeText(getActivity(),"立即拍照", Toast.LENGTH_SHORT).show();
                        et_time.setText("0");
                    }
//                    takePicture();
                } else if (mRecordingVideo == 1) {
                    Toast.makeText(getActivity(),"开始录像", Toast.LENGTH_SHORT).show();
                    // 设置开始计时时间
                    time.setVisibility(View.VISIBLE);
                    time.setBase(SystemClock.elapsedRealtime());
                    time.setFormat("录制时间： %s");
                    //启动计时器
                    time.start();
                    mMediaRecorder = new MediaRecorder();
                    startRecordingVideo();
                    // 隐藏按钮
                    iv_info.setVisibility(View.GONE);
                    iv_flash.setVisibility(View.GONE);
                    iv_setting.setVisibility(View.GONE);
                    iv_change.setVisibility(View.GONE);
                    mPicture_tv.setVisibility(View.GONE);
                    tv_slowMotion.setVisibility(View.GONE);
                    tv_delayed.setVisibility(View.GONE);
                    tv_pictures.setVisibility(View.GONE);
                    tv_videotapes.setVisibility(View.GONE);
                    tv_continuous.setVisibility(View.GONE);
                } else if (mRecordingVideo == 2) {
                    Toast.makeText(getActivity(),"停止录像", Toast.LENGTH_SHORT).show();
                    // 停止计时
                    time.setVisibility(View.GONE);
                    time.stop();
                    stopRecordingVideo();
                    iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_capture));
                    // 显示按钮
                    iv_info.setVisibility(View.VISIBLE);
                    iv_flash.setVisibility(View.VISIBLE);
                    iv_setting.setVisibility(View.VISIBLE);
                    iv_change.setVisibility(View.VISIBLE);
                    mPicture_tv.setVisibility(View.VISIBLE);
                    tv_slowMotion.setVisibility(View.VISIBLE);
                    tv_delayed.setVisibility(View.VISIBLE);
                    tv_pictures.setVisibility(View.VISIBLE);
                    tv_videotapes.setVisibility(View.VISIBLE);
                    tv_continuous.setVisibility(View.VISIBLE);
                }else if(mRecordingVideo == 4){
                    playSound(R.raw.camera_continue);
                    for(int i = 1; i <= Integer.parseInt(et_time.getText().toString()); i++) {
                        captureStillPicture();
                    }
                }
                break;
            }
            case R.id.pictures: { // 拍照
                mRecordingVideo = 3;
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.yx_btn));
                setmFile();
                ImageUtils.mDatas = ImageUtils.getThumbBitmapIndexs(getContext());
                et_time.setVisibility(View.GONE);
                et_time.setText("0");
                break;
            }
            case R.id.picture_iv: { // 打开相册
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivity(intent);
                et_time.setVisibility(View.GONE);
                et_time.setText("0");
                // 自定义相册
//                Intent intent = new Intent(getActivity(), PictureActivity.class);
//                startActivity(intent);
                break;
            }
            case R.id.change: { // 切换摄像头
                closeCamera();
                mCameraState = (mCameraState == 0) ? 1 : 0;
                //关闭闪光灯
                mFlash = 0;
                openCamera(mTextureView.getWidth(), mTextureView.getHeight());
                break;
            }
            case R.id.videotapes: { // 录像
                Toast.makeText(getActivity(),"录像", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_capture));
                mCaptureRate = 30;
                mRecordingVideo = 1;
                et_time.setVisibility(View.GONE);
                break;
            }
            case R.id.slowMotion: { //慢动作
                Toast.makeText(getActivity(),"慢动作", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.slowmotion));
                mRecordingVideo = 1;
                mCaptureRate = 120;
                et_time.setVisibility(View.GONE);
                break;
            }
            case R.id.delayed: {  //延时
                Toast.makeText(getActivity(),"延时", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.delayed));
                mRecordingVideo = 3;
                setmFile();
                ImageUtils.mDatas = ImageUtils.getThumbBitmapIndexs(getContext());
                et_time.setVisibility(View.VISIBLE);
                break;
            }
            case R.id.continuous: { //连拍
                Toast.makeText(getActivity(),"连拍两张", Toast.LENGTH_SHORT).show();
                iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.continuous));
                mRecordingVideo = 4;
                et_time.setVisibility(View.VISIBLE);
                break;
            }
            case R.id.flash: { //闪光灯
                if(mFlash == 0){
                    mFlash = 1;
                    Toast.makeText(getActivity(),"打开闪光灯", Toast.LENGTH_SHORT).show();
                }else{
                    mFlash = 0;
                    Toast.makeText(getActivity(),"关闭闪光灯", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case R.id.setting:{  //设置
                PopupMenu popup = new PopupMenu(getActivity(),view);
                popup.getMenuInflater().inflate(R.layout.menu_btn, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()){
                            case R.id.watermark:
                                String message = "加水印";
                                if(mWatermark == 1){
                                    textView.setVisibility(View.GONE);
                                    message = "不加水印";
                                }else{
                                    textView.setVisibility(View.VISIBLE);
                                }
                                mWatermark = mWatermark == 0 ? 1 : 0;
                                Toast.makeText(getActivity(),message, Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.ratio1:
                                Toast.makeText(getActivity(),"w:1456 h:1456",
                                        Toast.LENGTH_SHORT).show();
                                closeCamera();
                                mRatio = 1;
                                onResume();
                                break;
                            case R.id.ratio2:
                                Toast.makeText(getActivity(),"w:460 h:640",
                                        Toast.LENGTH_SHORT).show();
                                closeCamera();
                                mRatio = 2;
                                onResume();
                                break;
                            case R.id.ratio3:
                                Toast.makeText(getActivity(),"w:720 h:1280",
                                        Toast.LENGTH_SHORT).show();
                                closeCamera();
                                mRatio = 3;
                                onResume();
                                break;
                        }
                        return true;
                    }
                });
                popup.show();
                break;
            }
            case R.id.info: {
                Activity activity = getActivity();
                if (null != activity) {
                    new AlertDialog.Builder(activity)
                            .setMessage(R.string.intro_message)
                            .setPositiveButton(android.R.string.ok, null)
                            .show();
                }
                break;
            }

        }
    }

    private void setAutoFlash(CaptureRequest.Builder requestBuilder) {
        if (mFlashSupported) {
            requestBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                    CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
        }
    }

    //录像调用函数
    private boolean hasPermissionsGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(getActivity(), permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void requestVideoPermissions() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) {
            new PermissionDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
        } else {
            requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_VIDEO_PERMISSIONS);
        }
    }

    private void setUpCaptureRequestBuilder(CaptureRequest.Builder builder) {
        builder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
    }

    private void updatePreview() {
        if (null == mCameraDevice) {
            return;
        }
        try {
            setUpCaptureRequestBuilder(mPreviewRequestBuilder);
            HandlerThread thread = new HandlerThread("CameraPreview");
            thread.start();
            mPreviewSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    private String getVideoFilePath(Context context) {
        final File dir = context.getExternalFilesDir(null);
//        final File dir = MediaFunc.getOutputMediaFile(MediaFunc.MEDIA_TYPE_IMAGE, "VIDEO");
        System.out.println("===========VideoDir===========" + dir);
        //Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "Camera"+ "/"
        return (dir == null ? "" : (dir.getAbsolutePath() + "/")) + System.currentTimeMillis() + ".mp4";
    }

    private void setUpMediaRecorder() throws IOException {
        final Activity activity = getActivity();
        if (null == activity) {
            return;
        }
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        if (mNextVideoAbsolutePath == null || mNextVideoAbsolutePath.isEmpty()) {
            mNextVideoAbsolutePath = getVideoFilePath(getActivity());
        }
        mMediaRecorder.setOutputFile(mNextVideoAbsolutePath);
        mMediaRecorder.setVideoEncodingBitRate(10000000);
        mMediaRecorder.setCaptureRate(mCaptureRate);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        switch (mSensorOrientation) {
            case SENSOR_ORIENTATION_DEFAULT_DEGREES:
                mMediaRecorder.setOrientationHint(ORIENTATIONS.get(rotation));
                break;
            case SENSOR_ORIENTATION_INVERSE_DEGREES:
                mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
                break;
        }
        mMediaRecorder.prepare();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void startRecordingVideo() {
        playSound();
        if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
            return;
        }
        try {
            setUpMediaRecorder();
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
            mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
            List<Surface> surfaces = new ArrayList<>();

            // Set up Surface for the camera preview
            Surface previewSurface = new Surface(texture);
            surfaces.add(previewSurface);
            mPreviewRequestBuilder.addTarget(previewSurface);

            // Set up Surface for the MediaRecorder
            Surface recorderSurface = mMediaRecorder.getSurface();
            surfaces.add(recorderSurface);
            mPreviewRequestBuilder.addTarget(recorderSurface);

            // Start a capture session
            // Once the session starts, we can update the UI and start recording
            mCameraDevice.createCaptureSession(surfaces, new CameraCaptureSession.StateCallback() {

                @Override
                public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                    mPreviewSession = cameraCaptureSession;
                    updatePreview();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                         // UI
                            iv_pictures.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.mipmap.video_stop));
                            mRecordingVideo = 2;
                            // Start recording
                            mMediaRecorder.start();
                        }
                    });
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
                    Activity activity = getActivity();
                    if (null != activity) {
                        Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show();
                    }
                }
            }, mBackgroundHandler);
        } catch (CameraAccessException | IOException e) {
            e.printStackTrace();
        }

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void stopRecordingVideo() {
        // UI
//        mRecordingVideo = 3;
        // 停止录像
        mMediaRecorder.stop();
        mMediaRecorder.reset();

        Activity activity = getActivity();
        if (null != activity) {
            Toast.makeText(activity, "Video saved: " + mNextVideoAbsolutePath,
                    Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Video saved: " + mNextVideoAbsolutePath);
        }
        playSound();
        mNextVideoAbsolutePath = null;
        createCameraPreviewSession();
    }


    /**
     * 将JPEG {@link Image}保存到指定的{@link File}中。
     */
    private class ImageSaver implements Runnable {

        /**
         * JPEG图像
         */
        private final Image mImage;
        /**
         * 我们将图像保存到的文件。
         */
        private final File mFile;

        /**
         * 前后置摄像头切换参数，0：后置， 1：前置。
          */
        private int mCameraState;

        /**
         * 分辨率：0:原始分辨率  1：分辨率1456x1456   2：分辨率480x640   3：分辨率720x1280
         */
        private int mRatio;

        /**
         * 水印标志： 0: 不添加水印   1：添加水印
         */
        private int mWatermark;

        private Context mContext;

        ImageSaver(Image image, File file, int mCameraState, int ratio, int watermark, Context context) {
            mImage = image;
            mFile = file;
            this.mCameraState = mCameraState;
            this.mRatio = ratio;
            this.mWatermark = watermark;
            this.mContext = context;
        }

        @RequiresApi(api = Build.VERSION_CODES.Q)
        @Override
        public void run() {
            ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            int size = 300;
            int pointY = 300;
            FileOutputStream output = null;
            Canvas canvas;
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes,0,bytes.length);
            try {
                output = new FileOutputStream(mFile);
                // 前置摄像头水平翻转180
                if(mCameraState == 1){
                    Matrix m = new Matrix();
                    m.postScale(-1,1);
                    bitmap = Bitmap.createBitmap(bitmap,0,0,bitmap.getWidth(),bitmap.getHeight(),m,true);
                }
                if(mWatermark == 1){  // watermark == 1  加水印
                    Bitmap createBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.RGB_565);
                    if(mCameraState == 1) {
                        canvas = new Canvas(bitmap);
                    }else{
                        canvas = new Canvas(createBitmap);
                    }
                    // 分辨率改变影响到水印大小和位置
                    if(mRatio == 1){
                        size = 72;
                        pointY = 60;
                    }else if(mRatio == 2){
                        size = 32;
                        pointY = 30;
                    }else if(mRatio == 3){
                        size = 64;
                        pointY = 55;
                    }
                    // 加水印
                    canvas.drawBitmap(bitmap, 0, 0, null);
                    Paint paint = new Paint();
                    paint.setStyle(Paint.Style.FILL);
                    paint.setColor(Color.BLUE);
                    paint.setDither(true);
                    paint.setAntiAlias(true);
                    paint.setTextSize(size);
                    canvas.drawText("王靖", 0, pointY, paint);
                    if(mCameraState == 1){
                        bitmap.compress(Bitmap.CompressFormat.JPEG,100, output);
                    }else{
                        createBitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
                    }
                }else {
                    bitmap.compress(Bitmap.CompressFormat.JPEG,100,output);
                }
                System.out.println("======" + mFile.getPath());
                ImageUtils.insertToDB(mFile, mContext);
//                ImageUtils.insertToDB(mFile.getAbsolutePath(), mContext);
//                output.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                mImage.close();
                if (null != output) {
                    try {
                        output.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            //获取bitmap缩略图数据
            Bitmap bitmap2 = ThumbnailUtils.extractThumbnail(bitmap, 200, 200);
            picture = bitmap2;
            //发送绘制缩略图消息给Handler
            Message message = new Message();
            message.what = 1;
            pictureHandler.sendMessage(message);
//            mPicture_tv.setImageBitmap(ImageUtils.getLatestThumbBitmap());
        }
    }

    /**
     * 根据两个{@code Size}的面积进行比较。
     */
    static class CompareSizesByArea implements Comparator<Size> {

        @Override
        public int compare(Size lhs, Size rhs) {
            // 我们在这里进行转换以确保乘法不会溢出
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }
    }

//    public class FaceRunnable implements Runnable {
//
//        public FaceRunnable(CaptureResult result) {
//
//        }
//
//        @Override
//        public void run() {
//            onCameraImagePreviewed
//        }
//    }

    public Runnable timeRunnable = new Runnable() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void run() {

            int time = 0;
            time = Integer.parseInt(et_time.getText().toString());
            System.out.println("===============" + time);
            if (time > 0) {
//                try {
//                    Thread.sleep(1000);
//                    et_time.setText(String.valueOf(time - 1));
//                    mTimeHandler.post(timeRunnable);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                mTimeHandler.sendMessage(mTimeHandler.obtainMessage(CameraConstant.SEND_MESSAGE, time - 1));
                mTimeHandler.postDelayed(timeRunnable, 1000);
                isCountDownState = true;
            } else {
                et_time.setText("0");
                // 播放音频
                playSound();

                takePicture();

                isCountDownState = false;

            }
        }
    };

    /**
                * 播放音频
                */
        @RequiresApi(api = Build.VERSION_CODES.M)
        private void playSound() {
            MediaPlayer player = new MediaPlayer().create(this.getContext(), R.raw.camera);
            player.start();
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        private void playSound(final int audio) {
            MediaPlayer player = new MediaPlayer().create(this.getContext(), audio);
        player.start();
    }
}
